import json
import requests
from bs4 import BeautifulSoup
from merge_video_audio import merge_mp4
def get_url(base_url):
    ret = requests.get(base_url, headers={"Referer": "https://www.bilibili.com",
                                          "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
                                          })
    html = BeautifulSoup(ret.text, features="html.parser")
    scripts = html.select('html > head > script')
    file_name = html.select('html > head > title')[0].text
    data = json.loads(scripts[2].text.replace('window.__playinfo__=', ''))

    audio_url = data['data']['dash']['audio'][0]['baseUrl']
    video_url = data['data']['dash']['video'][0]['baseUrl']

    donwload_ma4(audio_url, file_name + 'audio')
    donwload_ma4(video_url, file_name + 'video')
    merge_mp4(file_name + 'audio', file_name + 'video')


def donwload_ma4(url, filename):
    ret = requests.get(url, headers={"Referer": "https://www.bilibili.com",
                                     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
                                     "range": "bytes=0-",
                                     })

    with open(f"{filename}.mp4", "wb") as f:
        f.write(ret.content)



base_url = "https://www.bilibili.com/video/BV17j411F7A8/"
get_url(base_url)
